<template>
  <div ref="contentContainer" class="content-container">
    
    <el-scrollbar
      class="content-component__scroll"
    >
      

      <!-- 富文本编辑器 -->
      <div class="rich-text-wrap">
        <!-- 标题 -->
        <el-input
            type="text"
            class="article-title"
            placeholder="请输入文章标题(5-30个汉字)"
            v-model="setting.title"
            maxlength="30"
            show-word-limit
        >
        </el-input>

        <div class="rich-text">
          
          <article-editor
            v-model="setting.content"
            @updateCacheImg="addImgToCache"
            @assist-api="assistDrawer"
          ></article-editor>

        </div>

        <!-- <el-button @click="test()">测试</el-button> -->

      </div>


      <!-- 文章发布设置 -->
      <div class="article-setting-wrap">
        
        <el-form
           class="setting-form"
          :model="setting"
          label-width="120px"

        >
          <el-form-item label="文章分类">
            
              <el-select v-model="setting.categoryId" clearable placeholder="请选择文章分类">
                <el-option
                  v-for="item in articleCata"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>

          </el-form-item>


          <el-form-item label="封面">
            
              <el-radio-group 

                v-model="setting.cover"
                text-color="#ff8100"
                @change="thumNumChange"
              >
                <el-radio label="1">单图</el-radio>
                <el-radio label="2">三图</el-radio>
                <el-radio label="3">无图</el-radio>
              </el-radio-group>

              <div class="thum-wrap" v-show="setting.cover != 3">

                <div 
                  v-for="(thum,key) in saveThumId"  
                  :key="key"
                  v-show="setting.cover == 1 ? key<1 : setting.cover == 2 ? key < 3 : key < 0" 
                  class="thum-item" 
                  @click="selectThum">
                  <div v-if="thum" class="thum-img-wrap">
                    <img :src="imgPrefix+thum">
                  </div>
                  <i v-if="!thum" class="el-icon-plus"></i>
                </div>
              </div>

          </el-form-item>


          <el-form-item label="设置">
            
              <el-radio-group 
                v-model="setting.advertising"
                text-color="#ff8100"
                @change="advsChange"
              >
                <el-radio label="1">投放广告</el-radio>
                <el-radio label="0">不投放广告</el-radio>
              </el-radio-group>

          </el-form-item>

          <el-form-item label="售卖方式">
            
              <el-radio-group 
                v-model="setting.saleWay"
                text-color="#ff8100"
                @change="saleTypeChange"
              >
                <el-radio :label="1">付费</el-radio>
                <el-radio :label="2">免费</el-radio>
                <el-radio :label="3">原创</el-radio>
              </el-radio-group>

          </el-form-item>


          <el-form-item label="商品价格">
            
              <el-input v-model="setting.goodsPrice" :disabled="setting.saleWay == 2"></el-input>
              <span class="input-unit">元</span>
          </el-form-item>
          
          <el-form-item label="阅读百分比">
            
              <el-input v-model="setting.readPercent" :disabled="setting.saleWay == 2" type="number"></el-input>
              <span class="input-unit">%</span>
          </el-form-item>

          <!-- 发布账号 -->
          <el-form-item label="账号">
            
              <select-account></select-account>

          </el-form-item>

        </el-form>

      </div>

      
      <!-- 操作栏 -->
      <div ref="footer" class="footer">
        <div class="footer-contain">
          <el-button type="primary" @click="saveHandler(1)">发表</el-button>
          <el-button @click="saveHandler(5)">定时发表</el-button>
          <el-button @click="savePreview(3)">保存并预览</el-button>
          <el-button @click="saveHandler(3)">存为草稿</el-button>
        </div>
      </div>


    </el-scrollbar>



    <!-- 选择缩略图 -->
    <select-thum
      :visible.sync="thumDialog"
      :data.sync="cacheImgs"
      :type.sync="setting.cover"
      :default-select="saveThumId"
      @close="thumSelectClose"
      @confirm="thumSelectConfirm"
    ></select-thum>


    <!-- 定时发表 -->
    <publish-time-dialog
      :visible="setTimingDialog"
      @cancel="publishTimeCancel"
      @comfirm="publishTimeComfirm"
    ></publish-time-dialog>


    <!-- 百度api文档 -->
    <article-drawer
      :visible="drawerVisible"
      :title="setting.title"
      :content="setting.content"
      :assistType.sync="assistType"
      @ecnet="assistDrawerEcnet"
      @summary="assistDrawerSummary"
      @close="assistDrawerClose"
    ></article-drawer>
  </div>

</template>

<script>
import { mapGetters } from 'vuex'
import { 
    save, 
    getMaterialList, 
    getImgInfo, 
    getArticleDetail,
    getBaiduAccessToken,
    bdApiHotList 
} from "@/api/substance/publish"


import ArticleEditor from "./articleEditor"
import PublishTimeDialog from "@/components/dingNiu/publishTimeDialog";
import SelectAccount from './selectAccount';
import SelectThum from './selectThum';
import ArticleDrawer from './articleDrawer'

import { getList } from "@/api/substance/articleTag"
import { baseUrl } from '@/config/env';
import { deepClone, getNowStr } from "@/utils/util"
import { validatenull, isNumber } from "@/utils/validate"

//获取图片的url
const imgPrefix = baseUrl+'/rest/common/preview/';

export default {
    components: {
      ArticleEditor,
      PublishTimeDialog,
      SelectThum,
      SelectAccount,
      ArticleDrawer
    },
    computed:{
      
    },
    data() {
        var _this = this;
        return {
            //百度api的显示/隐藏
            drawerVisible:false,
            assistType:'热点发现',
            //添加缩略图dialog
            thumDialog:false,
            //定时发表模态框
            setTimingDialog:false,

            //服务器图片前缀
            imgPrefix:imgPrefix,

            //正文图片插入缓存列表
            cacheImgs:[],
            //保存的缩略图id
            saveThumId:[],
            defaultSetting:{
              title:'',
              categoryId:'',
              cover:'-1',
              converIds:'',
              advertising:'-1',
              saleWay:-1,
              goodsPrice:'',
              subscribe:0,
              readPercent:'',
              updateTime:'',
              status:1,
              publishTime:'',
              content:'',
              imgsCache:'',
            },
            //文章设置
            setting:{
              title:'',
              categoryId:'',
              cover:'-1',
              converIds:'',
              advertising:'-1',
              saleWay:-1,
              goodsPrice:'',
              subscribe:0,
              readPercent:'',
              updateTime:'',
              status:1,
              publishTime:'',
              content:'',
              imgsCache:'',     //正文图片
            },
            //内容容器样式
            contentStyObj:null,
            footerStyObj:null,
            //文章分类
            articleCata:[],
            //富文本当前指针信息
            addRange:[],

            userInfo:null,
            access_token:'',
        }
    },
    created(){

    },
    mounted(){

      this.setSize();
      this.getArticleCata();
      this.getUserInfo();

      //判断是否有articleId,如果有就是编辑
      this.isEdit();

      //this.getBaiduAccessToken();
    },
    methods: {
        test(){
          bdApiHotList(this.access_token,'国际').then((res)=>{

            console.log("%c获取百度热点","background:#000;color:#fff");
            console.log(res)
            
          })
        },
        //获取百度accessToken
        getBaiduAccessToken(){
          getBaiduAccessToken().then((res)=>{

            console.log("%c获取百度access_token","background:#000;color:#fff");
            console.log(res)
            this.access_token = res.data.access_token;
          })
        },
        //调用百度辅助创作drawer
        assistDrawer(res){
          if(res.type == 1){
            this.assistType = "热点发现"
          }

          if(res.type == 2){
            this.assistType = "文本纠错"
          }

          if(res.type == 3){
            this.assistType = "发文助手"
          }
          this.drawerVisible = true;

        },
        assistDrawerClose(){
          this.drawerVisible = false;
        },
        //api纠错
        assistDrawerEcnet(res){
          var err = res.err;
          var advice = res.advice;
          alert(err+":"+advice)
          var result = this.setting.content.replace(new RegExp(err,'g'),advice)
          this.setting.content = result;
        },
        //api文章摘要
        assistDrawerSummary(summary){
          //将摘要添加至文章
          var summary = "<p>"+summary+"</p>";
          this.setting.content = summary+this.setting.content;
        },
        //编辑还是添加
        isEdit(){
          
          var articleId = this.$route.query.articleId;
          if(articleId !== undefined){
            //请求文章详情参数
            getArticleDetail(articleId).then((res)=>{
              console.log("-------获取文章详情----------")
              console.log(res)
              this.setting = res.data.data;
              //获取缩略图
              this.saveThumId = this.setting.converIds.split(',');
              //获取正文图片缓存
              this.cacheImgs = this.setting.imgsCache.split(',');
            })
          }
        },
        //获取用户信息
        getUserInfo(){
          this.$store.dispatch('user/GetUserInfo').then((userInfo)=>{
            console.log("------publish-获取用户信息------")
            console.log(userInfo);
            this.userInfo = userInfo;

          });
        },
        //设置元素的css属性
        setSize(){
          var containerWidth = this.$refs.contentContainer.offsetWidth;
          var footerHeight = this.$refs.footer.offsetHeight;

          this.contentStyObj = {
            'marginBottom':footerHeight+'px'
          }

          this.footerStyObj = {
            'width':containerWidth+'px'
          }

        },
        //将正文中添加的图片放入图片缓存
        addImgToCache(imgIds){
          this.cacheImgs = this.cacheImgs.concat(imgIds);
        },
        //选择缩略图
        thumSelectItemClick(item){
          item.selected = !item.selected;
        },
        //关闭选择缩略图模态框
        thumDialogClose(){
          this.thumDialog = false;
        },
        //确认选择的缩略图
        thumSelectConfirm(imgs){
          //1.判断单图or三图
          //循环缓存图片列表cacheImgs，筛选出已选择的图片
          //推入到缩略图选择列表saveThumId
          var select_arr = [];
          for(var i=0;i<imgs.length;i++){
            select_arr.push(imgs[i].fileId)
          }

          this.saveThumId = select_arr;
        },
 
        //封面图数量更改
        thumNumChange(value){
          this.setting.cover = value;
          if(value == 1){
            if(this.saveThumId.length < 1){
              this.saveThumId = [''];
            }
          }else if(value == 2){
            if(this.saveThumId.length < 3){
              for(let i=0;i<3;i++){

                if(typeof this.saveThumId[i] === 'undefined'){
                  this.saveThumId[i] = ''
                }
              }
            }
          }

          this.$forceUpdate();

        },
        //投放广告
        advsChange(value){
          this.setting.advertising = value;
        },
        //付费方式
        saleTypeChange(value){
          this.setting.saleWay = value;
        },
        //获取文章分类
        getArticleCata(){
          getList(1, 999).then(res => {
            this.articleCata = res.data.data;
          });
        },
        //验证保存的文章信息
        validateArticle(){
            //标题不能为空
            if(String(this.setting.title).trim().length == 0){
              this.$message({
                message:"文章标题不能为空",
                type:"error"
              })
              return false;
            }

            //文章内容验证
            if(String(this.setting.content).trim().length == 0){
              this.$message({
                message:"文章内容不能为空",
                type:"error"
              })
              return false;
            }

            //文章分类验证
            if(String(this.setting.categoryId).trim().length == 0){
              this.$message({
                message:"请选择文章分类",
                type:"error"
              })
              return false;
            }

            //文章分类验证
            if(this.setting.advertising < 0){
              this.$message({
                message:"请选择是否投放广告",
                type:"error"
              })
              return false;
            }

            //广告投放验证
            if(this.setting.cover < 0){
              this.$message({
                message:"请选择封面",
                type:"error"
              })
              return false;
            }


            //验证阅读百分比
            if(this.setting.readPercent !== "" && !isNumber(this.setting.readPercent)){
              this.$message({
                message:"阅读百分比为非负数字",
                type:"error"
              })
              return false;
            }

            return true;
        },
        //保存处理数据
        saveHandler(status){
          //验证发布信息
          if(!this.validateArticle()){
              return false;
          }

          //设置保存状态
          this.setting.status = status;
          
          //处理定时发布
          if(status == 5){
            this.setTimingDialog = true;
            return;
          }

          this.save();

        },
        //获取保存的缩略图
        getThum(){
          if(this.setting.cover == 1){
            if(this.saveThumId.length == 0 || validatenull(this.saveThumId[0])){
              this.$ipcTips.error('请选择缩略图');
              return false;
            }
            return [this.saveThumId[0]]

          }else if(this.setting.cover == 2){
            for(let i=0;i<3;i++){
              if(validatenull(this.saveThumId[i])){
                this.$ipcTips.error('请选择缩略图');
                return false;
              }
            }
            return this.saveThumId.splice(0,3)

          }else {
            return [];
          }
        },
        //调用接口保存至数据库
        save(callback){
            var send = deepClone(this.setting);
            send["userId"] = this.userInfo.id;
            var thums = this.getThum();
            console.log("------保存的时候获取缩略图------")
            console.log(thums)
            if(thums === false) {return false};
            //缩略图
            send["converIds"] = thums.join(",");
            //正文图片缓存
            send["imgsCache"] = this.cacheImgs.join(",");
            send["updateTime"] = getNowStr();      
            save(send).then((res)=>{

                console.log("-------文章编辑返回信息----------")
                console.log(res)

                if(res.data.code == 200){
                    this.$message({
                        type: 'success',
                        message: "保存成功"
                    });

                    //清空当前内容
                    this.setting = this.defaultSetting;

                    //如果有回调，调用回调
                    if(callback && typeof callback == 'function'){
                      callback(res.data.data)
                    }

                }else{
                    this.$message({
                        type: 'error',
                        message: "保存失败"
                    });
                }
            })
        },
        //保存并预览
        savePreview(status){
          var _this = this;
          //验证发布信息
          if(!this.validateArticle()){
              return false;
          }
          //设置保存状态
          this.setting.status = status;
          this.save(function(articleId){
            //跳转预览
            _this.$router.push({
              path:`/content/detail/${articleId}`
            })
          });
        },
        //选择缩略图
        selectThum(){
          this.thumDialog = true;
        },
        //取消发布时间
        publishTimeCancel(val){
          this.setting.publishTime = val;
          this.setTimingDialog = false;
        },
        //确认发布时间
        publishTimeComfirm(val){
          this.setting.publishTime = val;
          this.setTimingDialog = false;
          this.save();

        },
        //选择缩略图模态框关闭
        thumSelectClose(){
          this.thumDialog = false;
        }
    },
}
</script>


<style>
  .content-component__scroll{
    width: 100%;
    height: 100%;
    
  }
  .content-component__scroll .el-scrollbar__wrap{
    overflow-x: auto;
  }


  .setting-form .el-input{
    width: 200px;
  }

  .article-title{
    font-family: PingFangSC-Regular,Arial;
    min-height: 36px;
    font-weight: 700;
    font-size: 24px;
    line-height: 36px;
    color: #222;
    padding: 10px 0;
    background-color: transparent;
  }

  .article-title .el-input__inner{
    border-width: 0;
  }

  .img-upload-input .el-upload--picture-card{
    width: 100%;
    height: 100%;
    line-height: 180px;
  }
</style>


<style scoped>
  .input-unit{
    margin-left: 4px;
  }

  .rich-text-wrap{
    margin-top: 20px;
    padding: 0 20px;
  }

  .rich-text{
    position: relative;
    padding-bottom: 30px;
  }
  

  .article-setting-wrap{
    margin-top: 30px;
    padding: 0 20px;
  }

  .setting-form{
    width: 100%;
  }

  .footer{
    /*position: fixed;
    bottom: 0px;*/
    padding: 20px 40px;
    border-top: 1px solid rgb(232, 232, 232);
    z-index: 0;
    background-color: white;
    text-align: right;
    width: 100%;
  }


  /*添加缩略图按钮*/
  .thum-wrap{
    overflow: hidden;
  }
  .thum-item{
    width: 150px;
    height: 105px;
    border: 1px solid #e8e8e8;
    background-color: #f0f1f3;
    display: flex;
    justify-content: center;
    align-items: center;
    float: left;
    margin-right: 15px;
  }

  .thum-item .el-icon-plus{
    font-size: 30px;
    color: #ccc;

  }

  .thum-item img{
    width: 100%;
    height: 100%;
  }



</style>



<style lang="scss" scoped>
.content {
  &-container {
    height: 100%;
  }
  
}

</style>
